package logic

import (
	"context"
	"encoding/json"
	"product-mall/models/cache"
	"product-mall/models/mysql"
	"product-mall/productrpc/internal/svc"
	"product-mall/productrpc/productrpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type BrowseProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBrowseProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BrowseProductLogic {
	return &BrowseProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BrowseProductLogic) BrowseProduct(in *productrpc.BrowseProductRequest) (*productrpc.BrowseProductResponse, error) {
	// todo: add your logic here and delete this line
	var product []mysql.Product
	mysql.DB.Debug().Limit(20).Order("browse_number desc").Find(&product)

	var productList []*productrpc.BrowseProduct

	for _, m := range product {
		list := productrpc.BrowseProduct{
			Id:           int64(m.ID),
			Title:        m.Title,
			Price:        float32(m.Price),
			Image:        m.Image,
			ClassId:      m.ClassId,
			BrowseNumber: m.BrowseNumber,
		}
		productList = append(productList, &list)
	}

	marshal, _ := json.Marshal(product)
	cache.Rdb.Set(l.ctx, "browse20", marshal, time.Hour*24)
	return &productrpc.BrowseProductResponse{List: productList}, nil
}
